package com.hopedove.returnyarnsystem.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hopedove.base.BaseActivity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.CallReturnYarnBatch;
import com.hopedove.net.domain.Communication;
import com.hopedove.returnyarnsystem.R;
import com.hopedove.returnyarnsystem.constants.Constants;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.TipsDialogFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

@SuppressLint("UseSparseArrays")
public class MaterialInfoForBatchNoActivity extends BaseActivity implements OnClickListener {

    private JSONArray jsonArray = new JSONArray(); // 列表数据源
    private final HashMap<String, Boolean> isCheckMap = new HashMap<>(); // 存储选中的布料信息
    private final HashMap<String, String> numberMap = new HashMap<>();
    private TipsDialogFragment tipDialog;
    private String mCurrentJtNo = "";
    private Integer index = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_info_batchno);

        Intent intent = getIntent();
        try {
            jsonArray = new JSONArray(intent.getStringExtra(InputJTActivity.SOURCE_DATA));
            mCurrentJtNo = intent.getStringExtra(Constants.JT_NO);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        findViewById(R.id.call_img).setOnClickListener(this);
        findViewById(R.id.back_img).setOnClickListener(this);

        ListView listView = findViewById(R.id.info_listview);
        MyListAdapter mAdapter = new MyListAdapter();
        listView.setAdapter(mAdapter);
    }

    /**
     * 自定义adapter
     */
    class MyListAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String id = "";
            String Name = "";
            String Machineno = "";
            String fllx = "";
            String Number = "";

            if (jsonArray != null && jsonArray.length() > 0) {
                try {
                    // 获取每个item的数据
                    JSONObject jsonObject = jsonArray.getJSONObject(position);
                    id = jsonObject
                            .getString(Constants.MATERIAL_ID);
                    Name = jsonObject
                            .getString(Constants.MATERIAL_NAME);
                    Machineno = jsonObject
                            .getString(Constants.MATERIAL_MACHINENO);
                    fllx = jsonObject
                            .getString(Constants.MATERIAL_YLLX);
                    Number = jsonObject
                            .getString(Constants.MATERIAL_NUMBER);

                    if (Name == null || Name.equals("null")) {
                        Name = "";
                    }

                    if (Machineno == null || Machineno.equals("null")) {
                        Machineno = "";
                    }
                    if (Number == null || Number.equals("null")) {
                        Number = "";
                    }

                    if (fllx == null || fllx.equals("null")) {
                        fllx = "";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.list_item_batchno,
                        null);
                viewHolder.info_tv = convertView
                        .findViewById(R.id.info_tv);
                viewHolder.num_et = convertView
                        .findViewById(R.id.mnum_tv);
                viewHolder.machineNotv = convertView
                        .findViewById(R.id.machineNo_tv);
                viewHolder.fllx_tv = convertView
                        .findViewById(R.id.yl_tv);

                viewHolder.checkBtn = convertView
                        .findViewById(R.id.checkBox);

                viewHolder.num_et.setTag(position);
                viewHolder.num_et.setOnTouchListener((v, event) -> {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        index = (Integer) v.getTag();
                    }
                    return false;
                });

                class MyTextWatcher implements TextWatcher {
                    public MyTextWatcher(ViewHolder holder) {
                        mHolder = holder;
                    }

                    private ViewHolder mHolder;
                    private int editEnd;
                    private CharSequence temp;

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                                                  int count, int after) {
                        temp = s;
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        // 控制输入框只能接受5为数字，超过5位后，自动覆盖
                        editEnd = mHolder.num_et.getSelectionEnd();
                        if (temp.length() > 5) {
                            s.delete(0, editEnd - 1);
                            mHolder.num_et.setText(s);
                            mHolder.num_et.setSelection(editEnd + 1);
                        }
                        // 当EditText数据发生改变的时候存到NumberMap变量中
                        if (s != null && !"".equals(s.toString())) {
                            int position = (Integer) mHolder.num_et.getTag();
                            numberMap.put(String.valueOf(position),
                                    s.toString());
                        }
                    }

                }

                viewHolder.num_et.addTextChangedListener(new MyTextWatcher(
                        viewHolder));

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                viewHolder.num_et.setTag(position);
            }

            if (jsonArray != null && jsonArray.length() > 0) {
                viewHolder.info_tv.setText(Name);
                viewHolder.fllx_tv.setText(fllx);
                viewHolder.machineNotv.setText(Machineno);
                viewHolder.checkBtn.setTag(position);

                if (isCheckMap.containsKey("" + position)) {
                    viewHolder.checkBtn.setChecked(isCheckMap
                            .get("" + position));
                } else {
                    viewHolder.checkBtn.setChecked(false);
                }

                convertView.setOnClickListener(view -> {
                    ViewHolder viewHolder1 = (ViewHolder) view.getTag();
                    CheckBox checkBox = viewHolder1.checkBtn;

                    checkBox.setChecked(!checkBox.isChecked());

                    if (checkBox.isChecked()) {
                        isCheckMap.put(checkBox.getTag().toString(),
                                checkBox.isChecked());
                        ((TextView) findViewById(R.id.num_tv))
                                .setText(String.valueOf(isCheckMap.size()));
                    } else {
                        isCheckMap.remove(checkBox.getTag().toString());
                        ((TextView) findViewById(R.id.num_tv))
                                .setText(String.valueOf(isCheckMap.size()));
                    }
                });

                if (numberMap.get(String.valueOf(position)) != null
                        && !"".equals(numberMap.get(String.valueOf(position)))) {
                    viewHolder.num_et.setText(numberMap.get(String
                            .valueOf(position)));
                } else {
                    viewHolder.num_et.setText(Number);
                }
                viewHolder.num_et.clearFocus();
                if (index != -1 && index == position) {
                    viewHolder.num_et.requestFocus();
                }

            }

            return convertView;
        }

        public class ViewHolder {
            private TextView info_tv;
            private TextView machineNotv;
            private TextView fllx_tv;
            private EditText num_et;
            private CheckBox checkBtn;
        }

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.call_img) {
            if (isCheckMap.size() == 0) {
                Toast.makeText(getApplicationContext(), "请先选择需要的纱支",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            JSONArray jsonArray2 = new JSONArray();
            // 提取选择的信息
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    if (isCheckMap.containsKey("" + i)) {

                        if (numberMap.containsKey("" + i)) {
                            jsonObject.put(
                                    Constants.MATERIAL_NUMBER,
                                    numberMap.get(i + ""));
                        }
                        jsonArray2.put(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            tipDialog = TipsDialogFragment.showNewInstance(this, R.layout.return_view_tips_type_2, false);
            callReturnYarnInfo(jsonArray2);
        } else if (v.getId() == R.id.back_img) {
            finish();
        }
    }


    /**
     * 进行呼叫
     */
    void callReturnYarnInfo(final JSONArray obj) {

        try {
            JSONObject requestJSon = new JSONObject();
            JSONArray newJsonArray = new JSONArray();
            for (int i = 0; i < obj.length(); i++) {
                JSONObject json = obj.getJSONObject(i);
                JSONObject item = new JSONObject();
                item.put("MATERIAL_ID", json.opt(Constants.MATERIAL_ID));
                item.put("MATERIAL_NAME", json.opt(Constants.MATERIAL_NAME));
                item.put("MATERIAL_YLLX", json.opt(Constants.MATERIAL_YLLX));
                item.put("MATERIAL_NUMBER", json.opt(Constants.MATERIAL_NUMBER));
                item.put("MATERIAL_MACHINENO", json.opt(Constants.MATERIAL_MACHINENO));
                newJsonArray.put(item);
            }

            requestJSon.put("MACHINENO", mCurrentJtNo);
            requestJSon.put("RETURNYARNLIST", newJsonArray.toString());

            CallReturnYarnBatch callReturnYarnBatch = new CallReturnYarnBatch(requestJSon);
            Communication.asyncRequest(callReturnYarnBatch, r -> {

                if (r instanceof OkResponse) {
                    uiHandler.postDelayed(() -> {
                        TipsDialogFragment.dismissTipDialog(tipDialog);
                        Intent intent = new Intent(getApplicationContext(), ReturnYarnMainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }, 3000);
                } else if (r instanceof ErrResponse) {
                    ToastUtil.longToast(getBaseContext(), ((ErrResponse) r).getErrText());
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}
